'use client';

import trpc from '@/lib/trpc/client';
import { useState } from 'react';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import CreateEditAddress from './create-edit-address';

export default function AddressManage() {
  const [open, setOpen] = useState(false);
  const { data, isLoading } = trpc.address.listAllAddresses.useQuery(
    undefined,
    {
      enabled: open,
    },
  );
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="ghost">地址管理</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle>地址管理</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <div className="max-h-[400px] overflow-y-auto scrollbar-none">
          {data?.map((address) => (
            <div
              className="hover:bg-muted px-3 py-2 rounded-lg flex justify-between items-center transition-colors"
              key={address.id}
            >
              <div className="space-y-1 ">
                <div>{address.address}</div>
                <div className="text-xs text-muted-foreground space-x-1">
                  <span>{address.name}</span>
                  <span>{address.phone}</span>
                </div>
              </div>
              <CreateEditAddress
                type="edit"
                preData={address}
                button={
                  <span className="i-ri-edit-2-line cursor-pointer shrink-0" />
                }
              />
            </div>
          ))}
          {isLoading && (
            <div className="flex w-full h-full justify-center items-center">
              <span className="i-ri-loader-4-line animate-spin" />
            </div>
          )}
        </div>
        <div className="flex justify-end">
          <CreateEditAddress type="new" button={<Button>添加地址</Button>} />
        </div>
      </DialogContent>
    </Dialog>
  );
}
